package com.easylinkin.linkappapi.common.typehandler;

import cn.hutool.core.util.StrUtil;
import com.easylinkin.linkappapi.devicetype.entity.DeviceType;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

public class StringToListHandler extends BaseTypeHandler<List<String>> {
    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, List<String> strings, JdbcType jdbcType) throws SQLException {
        String ids = strings.stream().collect(Collectors.joining(","));
        preparedStatement.setString(i, ids);
    }

    @Override
    public List<String> getNullableResult(ResultSet resultSet, String s) throws SQLException {
        String string = resultSet.getString(s);
        List<String> deviceTypes = commonResult(string);
        return deviceTypes;
    }

    private List<String> commonResult(String string) {
        if (StrUtil.isBlank(string)) {
            return null;
        }
        List<String> stringList = new ArrayList<>();
        for (String id : string.split(",")) {
            stringList.add(id);
        }
        return stringList;
    }

    @Override
    public List<String> getNullableResult(ResultSet resultSet, int i) throws SQLException {
        Object object = resultSet.getObject(i);
        if(object!=null){
            List<String> stringList = commonResult((String) object);
            return stringList;
        }
        return null;
    }

    @Override
    public List<String> getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        Object object = callableStatement.getObject(i);
        if(object!=null){
            List<String> stringList = commonResult((String) object);
            return stringList;
        }
        return null;
    }
}
